import {
	defineStore
} from 'pinia'

import {
	wxLoginApi,
	douYinLoginApi
} from '@/service/api/index.js'

import {
	iscode
} from '@/utils/iscode.js'

const useLoginStore = defineStore('login', {
	state: () => ({
		token: "",
		refresh_token: "",
		userInfo: {}
	}),
	actions: {
		async loginAction(type = 'wx', payload) {
			let res = null

			if (type == 'dy') {
				res = await douYinLoginApi(payload)
			} else {
				res = await wxLoginApi(payload)
			}

			if (iscode(res)) {
				const {
					token,
					refresh_token,
					id,
					nickname,
					avatar,
					gender,
					last_login_time
				} = res.result

				this.$patch({
					token,
					refresh_token,
					userInfo: {
						id,
						nickname,
						avatar,
						gender,
						last_login_time
					}
				})
			}
		},
		logoutAction() {
			this.$reset()
		}
	},
	unistorage: {
		paths: ['token', 'refresh_token', 'userInfo']
	}
})

export default useLoginStore